﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

namespace ContentProcessor
{
    public class CDependencieConverter : TypeConverter
    {

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return (sourceType == typeof(string));
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return (destinationType == typeof(string));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            XmlSerializer _x = new XmlSerializer(typeof(List<KeyValuePair<string, string>>));
            using (MemoryStream _stream = new MemoryStream(Encoding.ASCII.GetBytes(value as string)))
            {
                using (XmlReader _r = XmlReader.Create(_stream))
                {
                    var _list = _x.Deserialize(_r) as List<KeyValuePair<string, string>>;
                    return _list.ToDictionary((kp) => { return kp.Key; },
                                              (kp) => { return kp.Value; });
                }
            }
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            Dictionary<string, string> _dico = value as Dictionary<string, string>;
            string export = "";
            foreach (var elem in _dico)
                export += elem.Key + "&" + elem.Value + "#";
            return export;
            //var _value = (from el in _dico select el).ToList();
            //XmlSerializer _x = new XmlSerializer(_value.GetType());
            //using (MemoryStream _stream = new MemoryStream())
            //{
            //    using (XmlWriter _w = XmlWriter.Create(_stream, new XmlWriterSettings() { Encoding = Encoding.ASCII,  Indent = false }))
            //    {
            //        _x.Serialize(_w, _value);
            //    }
            //    byte[] data = new byte[_stream.Length];
            //    _stream.Seek(0, SeekOrigin.Begin);
            //    _stream.Read(data, 0, (int)_stream.Length);
            //    return Encoding.ASCII.GetString(data);
            //}
        }
    }
}
